<template>
  <!-- 右下角固定的AI助手按钮 -->
  <div class="ai-assistant-button" @click="toggleDialog" v-if="(!isDialogOpen || isMinimized) && !isMobile">
    <div class="button-content">
      <el-icon class="button-icon"><ChatLineRound /></el-icon>
      <span class="button-text">宝可言</span>
    </div>
  </div>

  <!-- AI对话框 -->
  <div 
    v-if="isDialogOpen" 
    class="ai-dialog-container" 
    :class="{ 'minimized': isMinimized, 'maximized': isMaximized }"
  >
      <!-- 对话框头部 -->
      <div class="dialog-header">
        <div class="header-title">
          <span class="title-text"> 宝可言AI 助手</span>
        </div>
        <div class="header-actions">
          <el-icon class="action-icon" @click.stop="showDeleteConfirm" title="删除所有对话记录"><Delete /></el-icon>
          <!-- <el-icon class="action-icon" @click.stop="minimizeDialog" title="最小化"><Minus /></el-icon> -->
          <el-icon class="action-icon" @click.stop="maximizeDialog" :title="isMaximized ? '取消最大化' : '最大化'">
            <FullScreen v-if="isMaximized" />
            <FullScreen v-else />
          </el-icon>
          <el-icon class="action-icon close-icon" @click.stop="closeDialog" title="关闭"><Close /></el-icon>
        </div>
      </div>

      <!-- 对话框内容 -->
      <div class="dialog-content">
        <!-- 欢迎信息和推荐解决方案 -->
        <div class="welcome-and-solutions" v-if="chatMessages.length === 0">
          <!-- 欢迎信息 -->
          <div class="welcome-section">
            <!-- <div class="welcome-icon">
              <el-icon><ArrowRight /></el-icon>
            </div> -->
            <div class="welcome-text">
              <h2><span class="highlight-text">您好，我是 AI 助手</span></h2>
            </div>
          </div>

          <!-- 推荐解决方案 -->
          <div class="solutions-section">
            <div class="solution-card">
              <div class="solution-icon">
                <el-icon><ArrowDown /></el-icon>
              </div>
              <div class="solution-title">推荐解决方案</div>
              <div class="solution-list">
                <div class="solution-item" @click="selectSolution('如何进行退款')">
                  如何进行退款
                </div>
                <div class="solution-item" @click="selectSolution('如何进行余额充值')">
                  如何进行余额充值
                </div>
                <div class="solution-item" @click="selectSolution('如何联系客服')">
                  如何联系客服
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 对话历史 -->
        <div class="chat-history" v-else ref="chatHistoryRef">
          <div 
            v-for="(message, index) in chatMessages" 
            :key="index" 
            :class="['message', message.sender === 'user' ? 'user-message' : 'ai-message']"
          >
            <img 
              :src="message.sender === 'user' ? userAvatar : aiAvatar" 
              :alt="message.sender === 'user' ? '用户头像' : 'AI头像'"
              class="message-avatar"
            />
            <div class="message-content">
                <div class="message-bubble">
                  <div v-if="message.sender === 'ai'" v-html="message.content"></div>
                  <div v-else>{{ message.content }}</div>
                </div>
                <div class="message-time" v-if="message.time">{{ message.time }}</div>
              </div>
          </div>
          
          <!-- 加载动画显示在左侧，带头像和气泡 -->
          <div class="message ai-message" v-if="isLoading">
            <img :src="aiAvatar" alt="AI头像" class="message-avatar" />
            <div class="message-content">
              <div class="message-bubble loading-bubble">
                <div class="loading-spinner"></div>
                <span class="loading-text">正在思考中...</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 对话框底部 -->
      <div class="dialog-footer">
        <div class="input-container">
        <div class="chat-input-wrapper">
          <textarea
            v-model="userInput"
            class="chat-input"
            placeholder="请将您遇到的问题告诉我，使用 Shift + Enter 换行"
            @keyup.enter="sendMessage"
          ></textarea>
          <div class="input-actions">
            <button class="send-btn" @click="sendMessage" :disabled="!userInput.trim()">
              <el-icon class="send-icon"><Upload /></el-icon>
            </button>
          </div>
        </div>
      </div>
      </div>
    </div>
 
<!-- 删除确认对话框 -->
  <div v-if="isDeleteConfirmDialogVisible" class="delete-confirm-overlay" @click="hideDeleteConfirm">
    <div class="delete-confirm-dialog" @click.stop>
      <div class="delete-confirm-header">
        <h3>确认删除</h3>
      </div>
      <div class="delete-confirm-content">
        <p>确定要删除所有对话记录吗？此操作不可撤销。</p>
      </div>
      <div class="delete-confirm-footer">
        <button class="cancel-btn" @click="hideDeleteConfirm">取消</button>
        <button class="confirm-btn" @click="clearAllConversations">确定删除</button>
      </div>
    </div>
  </div>

  </template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, computed, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '../../stores/user';
import { 
  FullScreen,
  Close, 
  Delete,
  ArrowDown,
  ChatLineRound,
  // 发送
  Upload
} from '@element-plus/icons-vue';
import { useTokenStore } from '../../stores/token';
import { ElMessage } from 'element-plus';
import { getAllChatService, deleteAllChatService } from '../../api/ai';
import MarkdownIt from 'markdown-it';

// 初始化markdown解析器 - 允许HTML标签使<br>换行生效
const md = new MarkdownIt({
  html: true,         // 允许HTML标签，使<br>直接生效
  linkify: true,      // 自动将URL转换为链接
  typographer: true   // 启用一些语言中性的替换和引号美化
});

// 处理markdown内容，后端已返回<br>标签，直接渲染
const processMarkdown = (text: string) => {
  // 后端已处理换行为<br>标签，直接进行markdown渲染
  return md.render(text);
};

// 定义props，支持v-model
const props = defineProps<{
  visible?: boolean
}>();

// 定义emits，用于通知父组件状态变化
const emit = defineEmits<{
  'update:visible': [value: boolean]
}>();

// 对话框状态
const isDialogOpen = ref(props.visible || false);
const isMinimized = ref(false);
const isMaximized = ref(false);
const isLoading = ref(false);
const isMobile = ref(false);

// 检查是否为移动设备
const checkMobile = () => {
  isMobile.value = window.innerWidth < 768;
};

// 初始化时检查
onMounted(() => {
  checkMobile();
  window.addEventListener('resize', checkMobile);
});

// 清理事件监听器
onUnmounted(() => {
  window.removeEventListener('resize', checkMobile);
});

// 用户输入和AI响应
const userInput = ref('');
const aiResponse = ref('');
const conversations = ref<Array<{ question: string; answer: string }>>([]);
const chatMessages = ref<Array<{ sender: 'user' | 'ai'; content: string; time: string }>>([]);

// 创建模板引用
const chatHistoryRef = ref<HTMLDivElement | null>(null);

// 滚动到底部的函数
const scrollToBottom = () => {
  nextTick(() => {
    const el = chatHistoryRef.value;
    if (el) el.scrollTop = el.scrollHeight;
  });
};

// 获取用户store和router
const userStore = useUserStore();
const tokenStore = useTokenStore();
const router = useRouter();

// 头像配置
const userAvatar = computed(() => userStore.avatar );
const aiAvatar = ref(new URL('../../assets/ai.jpg', import.meta.url).href);

// 监听props变化，保持内部状态同步
watch(() => props.visible, (newValue) => {
  if (newValue !== undefined) {
    isDialogOpen.value = newValue;
  }
});

// 切换对话框显示/隐藏
const toggleDialog = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录后再使用AI助手');
    router.push('/login');
    return;
  }

  if (isMinimized.value) {
    // 从最小化状态恢复
    isMinimized.value = false;
    isMaximized.value = false;
  } else if (isDialogOpen.value) {
    // 如果已经打开，则关闭
    isDialogOpen.value = false;
    emit('update:visible', false);
  } else {
    // 打开对话框
    isDialogOpen.value = true;
    emit('update:visible', true);
    
    // 打开对话框时加载聊天记录
    if (tokenStore.token) {
      try {
        await fetchAllChatHistory();
      } catch (error) {
        console.error('加载聊天记录失败:', error);
      }
    }
  }
};

// 关闭对话框
const closeDialog = () => {
  isDialogOpen.value = false;
  isMinimized.value = false;
  isMaximized.value = false;
  emit('update:visible', false);
};

// 最小化对话框
// const minimizeDialog = () => {
//   isMinimized.value = true;
//   isMaximized.value = false;
// };

// 最大化对话框
const maximizeDialog = () => {
  if (isMaximized.value) {
    // 取消最大化
    isMaximized.value = false;
  } else {
    // 最大化
    isMaximized.value = true;
    isMinimized.value = false;
  }
};

// 确认删除对话框状态
const isDeleteConfirmDialogVisible = ref(false);

// 显示删除确认对话框
const showDeleteConfirm = () => {
  isDeleteConfirmDialogVisible.value = true;
};

// 隐藏删除确认对话框
const hideDeleteConfirm = () => {
  isDeleteConfirmDialogVisible.value = false;
};

// 删除所有对话记录
const clearAllConversations = async () => {
  try {
    await deleteAllChatService();
    chatMessages.value = [];
    conversations.value = [];
    isDeleteConfirmDialogVisible.value = false;
    ElMessage.success('删除成功');
  } catch (error) {
    console.error('删除聊天记录失败:', error);
    ElMessage.error('删除失败');
  }
};

// 选择推荐解决方案
const selectSolution = (solution: string) => {
  userInput.value = solution;
  sendMessage();
};

// 发送消息 - 使用fetch API实现流式回答
const sendMessage = async () => {
  const prompt = userInput.value.trim();
  if (!prompt) return;

  // 立即清空输入框
  userInput.value = '';
  
  isLoading.value = true;
  aiResponse.value = '';
  let fullAnswer = '';

  // 使用与后端一致的时间格式 YYYY-MM-DD HH:mm:ss
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  const currentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  
  chatMessages.value.push({ sender: 'user', content: prompt, time: currentTime });
  scrollToBottom();

  try {
    const response = await fetch(`/api/ai/streamChat?prompt=${encodeURIComponent(prompt)}`, {
      method: 'GET',
      headers: { 
        'Authorization': tokenStore.token || ''
      }
    });
    if (!response.ok) throw new Error(`请求失败: ${response.status}`);
    if (!response.body) throw new Error('响应体为空');

    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    
    // 添加AI消息占位符，用于流式响应（不显示时间）
    chatMessages.value.push({ sender: 'ai', content: '', time: '' });
    isLoading.value = false;

    // 处理SSE(text/event-stream)格式响应
    let buffer = '';
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      buffer += decoder.decode(value, { stream: true });
      
      // 处理SSE格式数据
      const lines = buffer.split('\n');
      buffer = lines.pop() || ''; // 保留不完整的最后一行
      
      for (const line of lines) {
        if (line.startsWith('data:')) {
          const data = line.slice(5).trim();
          if (data && data !== '[DONE]') {
            // 移除可能的引号
            const cleanData = data.replace(/^"|"$/g, '');
            fullAnswer += cleanData;
            
            // 使用processMarkdown处理内容，实时处理换行
            const renderedContent = processMarkdown(fullAnswer);
            chatMessages.value[chatMessages.value.length - 1].content = renderedContent;
            aiResponse.value = fullAnswer;
            scrollToBottom();

            // 检查结束标记
            if (cleanData.includes('[END]')) {
              fullAnswer = fullAnswer.replace(/\[END\]/g, '');
              chatMessages.value[chatMessages.value.length - 1].content = processMarkdown(fullAnswer);
              aiResponse.value = fullAnswer;
              break;
            }
          }
        }
      }
    }

    conversations.value.push({ question: prompt, answer: fullAnswer });
    scrollToBottom();
  } catch (error) {
    console.error('获取AI回答失败:', error);
    aiResponse.value = '抱歉，服务暂时不可用，请稍后再试。';
    const errorMessage = '抱歉，服务暂时不可用，请稍后再试。';
    const renderedErrorMessage = processMarkdown(errorMessage);
    
    if (chatMessages.value[chatMessages.value.length - 1].sender === 'ai') {
      chatMessages.value[chatMessages.value.length - 1].content = renderedErrorMessage;
    } else {
      chatMessages.value.push({ sender: 'ai', content: renderedErrorMessage, time: '' });
    }
  } finally {
    isLoading.value = false;
  }
};

// 获取所有聊天记录
const fetchAllChatHistory = async () => {
  try {
    const response = await getAllChatService();
    // 兼容多种返回结构：直接数组或 { data, code }
    const list = Array.isArray(response) ? response : response?.data;

    // 清空现有聊天记录
    chatMessages.value = [];

    if (Array.isArray(list) && list.length > 0) {
      list.forEach((chat: any) => {
        // 使用原始时间格式
        const time = chat.createTime;

        // 添加用户消息（包含时间）
        chatMessages.value.push({
          sender: 'user',
          content: chat.userMessage,
          time: time
        });

        // 添加AI回复消息（不包含时间）
        chatMessages.value.push({
          sender: 'ai',
          content: processMarkdown(chat.aiMessage),
          time: ''
        });
      });

      // 如果有聊天记录，滚动到底部
      nextTick(() => {
        scrollToBottom();
      });
    }

    // 控制台输出原始数据，便于排查
    console.log('聊天记录数据:', response);
  } catch (error) {
    console.error('获取聊天记录失败:', error);
    ElMessage.error('获取聊天记录失败');
  }
};

// 组件挂载时设置快捷键并获取聊天记录
onMounted(() => {
  const handleKeyDown = (event: KeyboardEvent) => {
    // Ctrl/Cmd + Shift + K 快速打开AI对话框
    if ((event.ctrlKey || event.metaKey) && event.shiftKey && event.key === 'K') {
      event.preventDefault();
      toggleDialog();
    }
  };

  document.addEventListener('keydown', handleKeyDown);
  
  // 获取聊天记录
  if (tokenStore.token) {
    fetchAllChatHistory();
  }

  // 组件卸载时清理事件监听
  // 在Vue 3中，我们可以在onUnmounted钩子中清理
  // 但由于我们使用的是script setup，所以需要返回清理函数
  return () => {
    document.removeEventListener('keydown', handleKeyDown);
  };
});
</script>

<style scoped lang="scss">
/* AI助手按钮样式 - 竖椭圆形状 */
.ai-assistant-button {
  position: fixed;
  bottom: 2rem;
  right: 5rem;
  width: 2rem;
  height: 5rem;
  background-color: #fff;
  border: 1px solid #ff7875;
  border-radius: 1.25rem;
  box-shadow: 0 3px 10px #f0dada;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  z-index: 1000;

  &:hover {
    transform: scale(1.1);
    // box-shadow: 0 6px 20px #ff7875;
  }

  .button-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: white;
    //橙色
    color: #ff7875;
  }

  .button-icon {
    // border-radius: 50%;
    // border: 1px solid #ff7875;
    font-size: 1.25rem;
    margin-bottom: 0.2rem;
  }

  .button-text {
    font-size: 0.8rem;
    font-weight: 700;
    writing-mode: vertical-rl;
    text-orientation: upright;
    letter-spacing: 0.1rem;
  }
}

/* 对话框容器 - 右下角固定浮框 */
.ai-dialog-container {
  position: fixed;
  bottom: 1rem;
  right: 1rem;
  width: 24rem; /* 增大宽度 */
  height: 36rem; /* 增大高度 */
  background: white;
  border-radius: 1rem;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  z-index: 2000;
  transition: all 0.3s ease;
}

/* 最小化样式 */
.ai-dialog-container.minimized {
  width: auto;
  height: auto;
  border-radius: 1rem;
  overflow: hidden;
}

.ai-dialog-container.minimized .dialog-content,
.ai-dialog-container.minimized .dialog-footer {
  display: none;
}

.ai-dialog-container.minimized .dialog-header {
  border-radius: 1rem;
  padding: 0.5rem 1rem;
}

/* 最大化样式 */
.ai-dialog-container.maximized {
  width: 90vw;
  height: 90vh;
  bottom: 5vh;
  right: 5vw;
  top: 5vh;
  left: 5vw;
  border-radius: 0;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .ai-dialog-container {
    width: 100vw;
    height: 100vh;
    bottom: 0;
    right: 0;
    left: 0;
    top: 0;
    border-radius: 0;
  }

  .ai-assistant-button {
    display: none;
  }
}

/* 对话框头部 */
.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 1.5rem;
  // border-bottom: 1px solid #e8e8e8;
  // background: linear-gradient(135deg, #fff0f6 0%, #e6f7ff 100%);
  background: linear-gradient(to top, #f0f9ff, #f5f4f4);

  .header-title {
    display: flex;
    align-items: center;
    gap: 0.5rem;

    .title-text {
      font-size: 1rem;
      font-weight: 600;
      color: #333;
    }

    .new-badge {
      background: #1890ff;
      color: white;
      font-size: 0.625rem;
      padding: 0.125rem 0.375rem;
      border-radius: 0.25rem;
    }
  }

  .header-actions {
    display: flex;
    align-items: center;
    gap: 1rem;

    .action-icon {
      color: #666;
      cursor: pointer;
      transition: color 0.2s;

      &:hover {
        color: #1890ff;
      }

      &.close-icon:hover {
        color: #ff4d4f;
      }
    }
  }
}

/* 对话框内容 */
.dialog-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: linear-gradient(to bottom, #f0f9ff, #ffffff);
 
}

/* 始终显示滚动条但优化其外观，避免内容位置变化 */
.welcome-and-solutions,
.chat-history {
  overflow-y: auto;
  padding-right: 1rem; /* 预留滚动条宽度 */
}

/* 优化滚动条样式 - 使其不占用内容空间 */
.welcome-and-solutions::-webkit-scrollbar,
.chat-history::-webkit-scrollbar {
  width: 0.25rem;
}

/* 滚动条轨道透明，使滚动条不明显但仍可用 */
.welcome-and-solutions::-webkit-scrollbar-track,
.chat-history::-webkit-scrollbar-track {
  background: transparent;
  border-radius: 0.125rem;
}

/* 滚动条滑块默认几乎透明，鼠标悬浮时显示 */
.welcome-and-solutions::-webkit-scrollbar-thumb,
.chat-history::-webkit-scrollbar-thumb {
  background: rgba(193, 193, 193, 0.3);
  border-radius: 0.125rem;
}

.welcome-and-solutions::-webkit-scrollbar-thumb:hover,
.chat-history::-webkit-scrollbar-thumb:hover {
  background: rgba(161, 161, 161, 0.6);
}

/* 欢迎区域 */
.welcome-section {
  display: flex;
  flex-direction: column;
  align-items: center;

  .welcome-icon {
    width: 5rem;
    height: 5rem;
    background: #f0f9ff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 1rem;

    .el-icon {
      
      font-size: 2rem;
      color: #597ef7;
      transform: rotate(45deg);
    }
  }

  .welcome-text h2 {
    font-size: 1.5rem;
    color: #333;
    text-align: center;
    margin: 0;

    .highlight-text {
      color: #597ef7;
    }
  }
}

/* 解决方案区域 */
.solutions-section {
  display: flex;
}

.solution-card {
  flex: 1;
  background: white;
  border: 1px solid #e8e8e8;
  border-radius: 0.5rem;
  padding: 1rem;
  transition: all 0.2s ease;

  &:hover {
    border-color: #597ef7;
    box-shadow: 0 2px 8px rgba(89, 126, 247, 0.1);
  }

  .solution-icon {
    width: 1.8rem;
    height: 1.8rem;
    background: #f0f9ff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 0.75rem;

    .el-icon {
      font-size: 1.25rem;
      color: #597ef7;
    }
  }

  .solution-title {
    font-size: 0.875rem;
    font-weight: 600;
    color: #333;
    margin-bottom: 0.75rem;
  }

  .solution-list {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
  }

  .solution-item {
    font-size: 0.8125rem;
    color: #666;
    padding: 0.5rem 0.75rem;
    background: #fafafa;
    border-radius: 0.25rem;
    cursor: pointer;
    transition: all 0.2s ease;

    &:hover {
      background: #f0f9ff;
      color: #597ef7;
    }
  }

  .query-button {
    font-size: 0.8125rem;
    color: #1890ff;
    padding: 0.5rem 0.75rem;
    background: #f0f9ff;
    border-radius: 0.25rem;
    text-align: center;
    cursor: pointer;
    transition: all 0.2s ease;

    &:hover {
      background: #e6f7ff;
      color: #40a9ff;
    }
  }
}

/* 对话历史 */
.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 1rem;
  padding-right: 1rem; /* 预留滚动条宽度 */
  display: flex;
  flex-direction: column;
  gap: 1rem;
  scrollbar-width: thin; /* Firefox */
  scrollbar-color: rgba(193, 193, 193, 0.3) transparent; /* Firefox */
}

/* 消息样式 */
.message {
  display: flex;
  gap: 0.75rem;
  align-items: flex-start;
}

/* 用户消息样式 */
.user-message {
  justify-content: flex-end;
}

.user-message .message-content {
  order: -1;
  align-items: flex-end;
}

/* AI消息样式 */
.ai-message {
  justify-content: flex-start;
}

.ai-message .message-content {
  align-items: flex-start;
}

/* 消息头像 */
.message-avatar {
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 50%;
  object-fit: cover;
  flex-shrink: 0;
}

/* 消息内容 */
.message-content {
  display: flex;
  flex-direction: column;
  max-width: 70%;
  gap: 0.25rem;
}

/* 消息气泡 */
.message-bubble {
  max-width: 100%;
  padding: 0.75rem 1rem;
  border-radius: 0.75rem;
  font-size: 0.875rem;
  line-height: 1.5;
  word-wrap: break-word;
  overflow-wrap: break-word;
  box-sizing: border-box;
}

.user-message .message-bubble {
  background: #597ef7;
  background-color: rgb(231, 241, 253);
  color: white;
  color: #333;
  border-bottom-right-radius: 0.25rem;
}

.ai-message .message-bubble {
  background: linear-gradient(135deg, rgb(239, 241, 253) 0%, rgb(255, 246, 249) 100%);
  color: #333;
  border-bottom-left-radius: 0.25rem;
  white-space: normal;
  word-break: break-word;
}

/* Markdown样式 */
.ai-message .message-bubble p {
  margin: 0.5rem 0;
  max-width: 100%;
  box-sizing: border-box;
}

.ai-message .message-bubble p:first-child {
  margin-top: 0;
}

.ai-message .message-bubble p:last-child {
  margin-bottom: 0;
}

.ai-message .message-bubble ul, 
.ai-message .message-bubble ol {
  margin: 0.5rem 0;
  padding-left: 1.5rem;
  max-width: 100%;
  box-sizing: border-box;
}

.ai-message .message-bubble code {
  background-color: rgba(0, 0, 0, 0.05);
  padding: 0.2rem 0.4rem;
  border-radius: 0.25rem;
  font-family: monospace;
  font-size: 0.9em;
  word-break: break-word;
}

.ai-message .message-bubble pre {
  background-color: rgba(0, 0, 0, 0.05);
  padding: 0.75rem;
  border-radius: 0.25rem;
  overflow-x: auto;
  margin: 0.5rem 0;
  max-width: 100%;
  box-sizing: border-box;
}

.ai-message .message-bubble pre code {
  background-color: transparent;
  padding: 0;
  border-radius: 0;
  word-break: break-word;
}

.ai-message .message-bubble blockquote {
  border-left: 4px solid #ddd;
  padding-left: 1rem;
  margin-left: 0;
  color: #666;
  max-width: 100%;
  box-sizing: border-box;
}

/* 消息时间 */
.message-time {
  font-size: 0.75rem;
  color: #999;
}

/* 欢迎信息和解决方案容器 */
.welcome-and-solutions {
  padding: 1.5rem;
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  overflow-y: hidden;
  max-height: 100%;
}

/* 聊天历史滚动条样式 */
.chat-history::-webkit-scrollbar {
  width: 0.25rem;
}

.chat-history::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 0.125rem;
}

.chat-history::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 0.125rem;
}

.chat-history::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1;
}

/* 加载指示器 */
/* 加载动画气泡 */
.loading-bubble {
  display: flex;
  align-items: center;
  background: linear-gradient(135deg, rgb(239, 241, 253) 0%, rgb(255, 246, 249) 100%);
  padding: 0.5rem 0.75rem;
  border-radius: 0.75rem;
  border-bottom-left-radius: 0.25rem;
}

.loading-spinner {
  width: 1rem;
  height: 1rem;
  border: 2px solid #f3f3f3;
  border-top: 2px solid #597ef7;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-right: 0.5rem;
}

.loading-text {
  font-size: 0.875rem;
  color: #666;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* AI回答 */
.ai-answer {
  background: white;
  border-radius: 0.5rem;
  padding: 1rem;
  margin-bottom: 1rem;

  .answer-content {
    font-size: 0.875rem;
    color: #333;
    line-height: 1.5;
  }
}

/* 删除确认对话框覆盖层 */
.delete-confirm-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 3000;
}

/* 删除确认对话框 */
.delete-confirm-dialog {
  background: white;
  border-radius: 0.75rem;
  padding: 1.5rem;
  width: 25rem;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.delete-confirm-header {
  margin-bottom: 1rem;
  border-bottom: 1px solid #e8e8e8;
  padding-bottom: 0.75rem;
}

.delete-confirm-header h3 {
  margin: 0;
  font-size: 1rem;
  font-weight: 600;
  color: #333;
}

.delete-confirm-content {
  margin-bottom: 1.5rem;
}

.delete-confirm-content p {
  margin: 0;
  font-size: 0.875rem;
  color: #666;
  line-height: 1.5;
}

.delete-confirm-footer {
  display: flex;
  justify-content: flex-end;
  gap: 0.75rem;
}

.cancel-btn,
.confirm-btn {
  padding: 0.5rem 1.25rem;
  border: none;
  border-radius: 0.25rem;
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.2s;
}

.cancel-btn {
  background: #f5f5f5;
  color: #666;
  border: 1px solid #d9d9d9;
}

.cancel-btn:hover {
  background: #f0f0f0;
  border-color: #bfbfbf;
}

.confirm-btn {
  background: #ff4d4f;
  color: white;
}

.confirm-btn:hover {
  background: #ff7875;
}

/* 对话框底部 */
.dialog-footer {
  padding: 1rem 1.5rem;
  background: linear-gradient(to top, #f0f9ff, #ffffff);
}

.input-container {
  position: relative;
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.chat-input-wrapper {
  display: flex;
  align-items: center;
  width: 100%;
  position: relative;
}

.markdown-hint {
  font-size: 0.75rem;
  color: #888;
  margin-bottom: 0.25rem;
  text-align: left;
}

.chat-input {
  width: 100%;
  min-height: 3.75rem;
  max-height: 7.5rem;
  padding: 0.75rem 3rem 0.75rem 0.75rem; /* 为右侧的发送按钮留出空间 */
  border: 1px solid #e0e0e0;
  border-radius: 0.25rem;
  resize: none; /* 移除下拉调整大小功能 */
  font-size: 0.875rem;
  font-family: inherit;
  outline: none;
  background: #ffffff;
  transition: border-color 0.2s;
  box-shadow: none; /* 移除内部阴影 */

  &:focus {
    border-color: #597ef7;
    box-shadow: 0 0 0 2px rgba(89, 126, 247, 0.1);
    background: #ffffff;
  }

  &:hover:not(:focus) {
    border-color: #c0c0c0;
  }
}

.input-actions {
  position: absolute;
  right: 0.5rem;
  bottom: 0.5rem;
  display: flex;
  align-items: center;
}


.send-btn {
  width: 1.8rem;
  height: 1.8rem;
  background: #597ef7;
  border: none;
  border-radius: 50%;
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
  z-index: 10;

  &:hover:not(:disabled) {
    background: #4096ff;
    transform: scale(1.05);
  }

  &:disabled {
    color: #597ef7;
    background: #fff;
    cursor: not-allowed;
  }
  .send-icon {
    font-size: 1.2rem;
    font-weight: 700;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .ai-dialog-container {
    width: 95vw;
    height: 90vh;
  }

  .solutions-section {
    flex-direction: column;
  }
}
</style>